<template>
  <div>
    <div id="qrCode" ref="qrCodeDivRef">
    </div>
    <a ref="qrCodeDownloadLinkRef" style="display: none"></a>
    <button type="primary" @click="downLoadQrcode">下载</button>
    <!-- <button type="primary" @click="downLoadQrcode2">下载</button> -->
    <!-- <button type="primary" @click="download">down</下载> -->
  </div>
</template>
<script>
import QRCode from 'qrcodejs2'

    /**
      * 二维码生成
      * @param content 生成二维码内容
      * @param desc 二维码底部描述
      * @param qrcodeDom 挂在dom
      * @returns {*|HTMLDivElement}
     */
     function generatorQrcode(content, desc, qrcodeDom = null) {
      const qrcodeContent = qrcodeDom || document.createElement('div');
      qrcodeContent.width = '400px';
      qrcodeContent.height = '400px';
      const qrcodeCanvas = new QRCode(qrcodeContent, {
        text: content, // 需要转换为二维码的内容
        width: 300,
        height: 300,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      });
      var resolutionMultiple = 1; // 分辨率倍数
      var borderSize = 5 * resolutionMultiple; // 边框留白
      var canvasWidth = 300 * resolutionMultiple; // 图片宽度
      // 判断 参数为空的命名情况
      var text = desc || '';// 底部文字
      var fontSize = 16 * resolutionMultiple; // 文字大小

      // var canvasHeight = canvasWidth + fontSize * 5;
      var canvasHeight = canvasWidth + fontSize;
      var canvas = document.createElement('canvas');
      if (!canvas.getContext) return
      canvas.width = canvasWidth;
      canvas.height = canvasHeight;

      var ctx = canvas.getContext('2d');
      ctx.fillStyle = 'rgb(255,255,255)'; // 调色(纯白)
      ctx.fillRect(0, 0, canvasWidth, canvasHeight); // 绘制背景

      var qrcodeSize = canvasWidth - borderSize * 2;
      ctx.drawImage(
        qrcodeContent.querySelector('canvas'),
        borderSize,
        borderSize,
        qrcodeSize,
        qrcodeSize
      ); // 填充二维码

      ctx.fill(); // 填充背景

      ctx.fillStyle = 'rgb(0,0,0)' // 调色(纯黑)
      ctx.font = fontSize + 'px Arial' // 文本大小, 字体
      ctx.textAlign = 'center'
      //处理文字描述太长换行问题
      ctx = drawText(ctx, text, canvasWidth / 2, qrcodeSize + borderSize, qrcodeSize)
      // ctx.fillText(
      //   text,
      //   canvasWidth / 2,
      //   qrcodeSize + borderSize,
      //   qrcodeSize
      // ) // 绘制文本
      // 清除原二维码
      // qrcodeCanvas.clear()
      qrcodeContent.appendChild(canvas);
      Array.from(qrcodeContent.querySelectorAll('img')).forEach((item) => {
      // item.style.display = 'none'
      item.remove()
        // console.log('img', item)
      })
      return qrcodeContent
    }
    /**
     *  文字换行
     * canvas文本换行处理
     * @param ctx canvas的 2d 对象
     * @param desc 绘制的文字
     * @param x 文字X坐标
     * @param y 文字Y坐标
     * @param w 文字最大宽度
     * @param space 每行字体y坐标间隔默认17
     */
    function drawText (ctx, desc, x, y, w, space = 17) {
      // ctx：canvas的 2d 对象，t：绘制的文字，x,y:文字坐标，w：文字最大宽度
      const chr = desc;
      let temp = '';
      const row = [];
      for (let a = 0; a < chr.length; a++) {
        if (ctx.measureText(temp).width < w && ctx.measureText(temp + (chr[a])).width <= w) {
          temp += chr[a]
        } else {
          row.push(temp)
          temp = chr[a]
        }
      }
      row.push(temp)
      for (let b = 0; b < row.length; b++) {
        ctx.fillText(row[b], x, y + (b + 1) * space)// 每行字体y坐标间隔20
      }
      return ctx
    }

export default {
  // components: [],
  props:{
    //必传，且为 String 类型
    contentText: {
      type: String,
      required: true
    },
    bottomText: String
  },
  data() {
    return {
      // contentText: 'hahha',
      // bottomText: '底部文字'
    };
  },
  created() {},
  mounted() {
    this.getQRCode();
    //使用生成二维码
    //generatorQrcode(this.contentText, this.bottomText, this.$refs.qrCodeDivRef);
  },
  methods: {
    getQRCode() {
      new QRCode(this.$refs.qrCodeDivRef,{
        text: this.contentText, // 需要变成二维码的文本
        width: 260,
        height: 260,
        colorDark: '#333', // 二维码颜色
        colorLight: '#fff', // 二维码背景颜色
        correctLevel: QRCode.CorrectLevel.L //容错率,L/M/H
      });
      let qrCodeDiv = this.$refs.qrCodeDivRef;
      let qrCodeDivCanvas = qrCodeDiv.getElementsByTagName('canvas');//get all canvas
      let qrcodeCanvas = null;
      if (qrCodeDivCanvas !== undefined && qrCodeDivCanvas.length>0) {
        qrcodeCanvas = qrCodeDivCanvas[0];
        this.qrcodeImgUrl = qrcodeCanvas.toDataURL("image/png");
      } else {
        qrcodeCanvas = [];
        this.qrcodeImgUrl = "";
      }
      //this.qrcodeImgUrl = ""; // 作为下载图片资源
    },
    //有a标签
    downLoadQrcode() {
      let downloadLink = this.$refs.qrCodeDownloadLinkRef;
      downloadLink.setAttribute('href', this.qrcodeImgUrl);
      downloadLink.setAttribute(
        'download',
        `二维码_${new Date().getTime()}.png`
      );
      // downloadLink.style.display = 'none';
      downloadLink.click();
      URL.revokeObjectURL(downloadLink.href);
    },
    //没有a标签
    downLoadQrcode2() {
      const a = document.createElement('a');
      a.setAttribute('href', this.qrcodeImgUrl);
      a.setAttribute('download',`二维码_${new Date().getTime()}.png`);
      a.style.display = 'none';
      let qrCodeDiv = this.$refs.qrCodeDivRef;
      qrCodeDiv.appendChild(a);
      a.click();
      qrCodeDiv.removeChild(a);
    },
    //generatorQrcode
    download () {
      const a = document.createElement('a');
      a.setAttribute('download',`二维码_${new Date().getTime()}.png`);
      a.style.display = 'none';
      //获取二维码画布,实质是canvas节点
      let qrCodeDiv = this.$refs.qrCodeDivRef;
      a.href = qrCodeDiv.children[1].toDataURL('image/png', 0.5);
      qrCodeDiv.appendChild(a);
      a.click();
      qrCodeDiv.removeChild(a);
    },
  }
}
</script>

<style scoped>

</style>